import React, { useEffect, useState, forwardRef, ForwardedRef } from 'react'
import { useNavigate } from 'react-router-dom'
import './video.css'
import { FixedSizeList as List } from 'react-window'

interface VideoItem {
  name: string;
  introduce: string;
  comment: string;
  video: string;
  avatar: string;
}

const VideoCard = ({ data, index, style }: { data: VideoItem[], index: number, style: React.CSSProperties }) => {
  const item = data[index];
  const navigate = useNavigate();

  const handleVideoClick = () => {
    navigate('/video/detail', {
      state: {
        video: item.video,
        name: item.name,
        avatar: item.avatar,
        introduce: item.introduce,
        comment: item.comment
      }
    });
  };

  return (
    <div style={style} className="video-card" onClick={handleVideoClick}>
      <div className="video-header">
        <div className="user-avatar">
          <img src={item.avatar} alt="user avatar" loading="lazy" />
        </div>
        <div className="user-info">
          <div className="username">{item.name}</div>
          <div className="description">{item.introduce}</div>
        </div>
        <button className="follow-btn">关注</button>
      </div>

      <div className="video-player-container">
        <video
          className="video-player"
          src={item.video}
          loop
          controls
          playsInline
        />
      </div>

      <div className="video-actions">
        <div className="action-item">
          <span className="action-icon">❤️</span>
          <span className="action-count">0</span>
        </div>
        <div className="action-item">
          <span className="action-icon">💬</span>
          <span className="action-count">0</span>
        </div>
        <div className="action-item">
          <span className="action-icon">⤴️</span>
          <span className="action-count">0</span>
        </div>
      </div>

      <div className="video-comments">
        <div className="comment-text">{item.comment}</div>
      </div>
    </div>
  );
};

const Video = forwardRef((props, ref: ForwardedRef<HTMLDivElement>) => {
  const [videoList, setVideoList] = useState<VideoItem[]>([]);
  const [currentCategory, setCurrentCategory] = useState('');
  const [categories, setCategories] = useState<string[]>([]);

  const fetchCategories = async () => {
    try {
      const response = await fetch('http://localhost:3000/cate');
      const data = await response.json();
      if (data.code === 200) {
        const categoryNames = data.data.map((item: { name: string }) => item.name);
        setCategories(categoryNames);
        if (categoryNames.length > 0) {
          setCurrentCategory(categoryNames[0]);
        }
      }
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

  const fetchVideosByCategory = async () => {
    try {
      const response = await fetch('http://localhost:3000/people');
      const data = await response.json();
      if (data.code === 200) {
        setVideoList(data.data);
      }
    } catch (error) {
      console.error('Error fetching videos:', error);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    if (currentCategory) {
      fetchVideosByCategory();
    }
  }, [currentCategory]);

  return (
    <div className="video-container" ref={ref}>
      <div className="category-nav">
        {categories.map((category, index) => (
          <div
            key={index}
            className={`category-item ${currentCategory === category ? 'active' : ''}`}
            onClick={() => setCurrentCategory(category)}
          >
            {category}
          </div>
        ))}
      </div>
      <div className="video-feed">
        <List
          height={window.innerHeight - 100}
          itemCount={videoList.length}
          itemSize={380}
          width="100%"
          itemData={videoList}
        >
          {VideoCard}
        </List>
      </div>
    </div>
  );
});

export default Video;
